<template>
  <div class="invoice-edit-container">
    <el-card class="edit-card">
      <template #header>
        <div class="card-header">
          <span>{{ !props.invoiceId ? '新增销项发票' : (props.operation === 'view' ? '查看销项发票' : '编辑销项发票') }}</span>
          <div class="header-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit" v-if="props.operation !== 'view'">保存</el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        :disabled="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="formData.invoiceCode" placeholder="请输入发票代码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceTypeCode">
              <el-select v-model="formData.invoiceTypeCode" placeholder="请选择发票类型" style="width: 100%">
                <el-option label="增值税专用发票" value="special" />
                <el-option label="增值税普通发票" value="normal" />
                <el-option label="电子发票" value="electronic" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否红字发票" prop="isRedInvoice">
              <el-radio-group v-model="formData.isRedInvoice">
                <el-radio :value="'Y'">是</el-radio>
                <el-radio :value="'N'">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="formData.invoiceDate"
                type="date"
                placeholder="请选择开票日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="formData.customerId" placeholder="请选择客户" style="width: 100%">
                <el-option label="杭州华采供应链有限公司" value="1" />
                <el-option label="浙江医药股份有限公司" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销方识别号" prop="sellerTaxNumber">
              <el-input v-model="formData.sellerTaxNumber" placeholder="请输入销方识别号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销方名称" prop="sellerName">
              <el-input v-model="formData.sellerName" placeholder="请输入销方名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购方识别号" prop="buyerTaxNumber">
              <el-input v-model="formData.buyerTaxNumber" placeholder="请输入购方识别号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购方名称" prop="buyerName">
              <el-input v-model="formData.buyerName" placeholder="请输入购方名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金额" prop="totalAmount">
              <el-input-number
                v-model="formData.totalAmount"
                placeholder="请输入金额"
                :precision="2"
                :step="100"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税额" prop="taxAmount">
              <el-input-number
                v-model="formData.taxAmount"
                placeholder="请输入税额"
                :precision="2"
                :step="10"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价税合计" prop="totalTaxAmount">
              <el-input-number
                v-model="formData.totalTaxAmount"
                placeholder="请输入价税合计"
                :precision="2"
                :step="100"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票人" prop="issuer">
              <el-input v-model="formData.issuer" placeholder="请输入开票人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="税务机关代码" prop="taxBureauCode">
              <el-input v-model="formData.taxBureauCode" placeholder="请输入税务机关代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税务机关名称" prop="taxBureauName">
              <el-input v-model="formData.taxBureauName" placeholder="请输入税务机关名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getOutgoingInvoiceById, createOutgoingInvoice, updateOutgoingInvoice } from '@/api/invoice'

// 路由
const route = useRoute()
const router = useRouter()

// 定义props
const props = defineProps({
  operation: {
    type: String as () => 'add' | 'edit' | 'view',
    default: 'add'
  },
  invoiceId: {
    type: [String, Number],
    default: undefined
  }
})

// 定义emits
const emit = defineEmits(['save-success', 'cancel'])

// 是否为编辑模式
const isEdit = computed(() => {
  return props.operation === 'edit' && !!props.invoiceId
})

// 加载状态
const loading = ref(false)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  id: '',
  invoiceNumber: '',
  invoiceCode: '',
  invoiceTypeCode: '',
  isRedInvoice: 'N',
  invoiceDate: '',
  customerId: '',
  sellerTaxNumber: '',
  sellerName: '',
  buyerTaxNumber: '',
  buyerName: '',
  totalAmount: 0,
  taxAmount: 0,
  totalTaxAmount: 0,
  issuer: '',
  taxBureauCode: '',
  taxBureauName: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  invoiceNumber: [
    { required: true, message: '请输入发票号码', trigger: 'blur' }
  ],
  invoiceCode: [
    { required: true, message: '请输入发票代码', trigger: 'blur' }
  ],
  invoiceTypeCode: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  invoiceDate: [
    { required: true, message: '请选择开票日期', trigger: 'change' }
  ],
  sellerTaxNumber: [
    { required: true, message: '请输入销方识别号', trigger: 'blur' }
  ],
  sellerName: [
    { required: true, message: '请输入销方名称', trigger: 'blur' }
  ],
  buyerTaxNumber: [
    { required: true, message: '请输入购方识别号', trigger: 'blur' }
  ],
  buyerName: [
    { required: true, message: '请输入购方名称', trigger: 'blur' }
  ],
  totalAmount: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ],
  taxAmount: [
    { required: true, message: '请输入税额', trigger: 'blur' }
  ],
  totalTaxAmount: [
    { required: true, message: '请输入价税合计', trigger: 'blur' }
  ]
}

// 取消
const handleCancel = () => {
  emit('cancel')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        // 确保isRedInvoice字段符合类型要求
        const submitData: any = {
          ...formData,
          isRedInvoice: formData.isRedInvoice === 'Y' ? 'Y' : 'N'
        }
        
        let response
        if (props.operation === 'add') {
          // 新增发票
          response = await createOutgoingInvoice(submitData)
        } else {
          // 编辑发票
          response = await updateOutgoingInvoice(formData.id, submitData)
        }
        
        if (response) {
          ElMessage.success(`${props.operation === 'add' ? '新增' : '更新'}销项发票成功`)
          emit('save-success')
        } else {
          ElMessage.error(`${props.operation === 'add' ? '新增' : '更新'}销项发票失败`)
        }
      } catch (error: any) {
        ElMessage.error(`${props.operation === 'add' ? '新增' : '更新'}销项发票失败: ${error.message || '未知错误'}`)
      } finally {
        loading.value = false
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(async () => {
  // 根据操作类型和发票ID获取数据
  if (props.operation === 'edit' && props.invoiceId) {
    loading.value = true
    try {
      // 调用后端API获取发票详情
      const data: any = await getOutgoingInvoiceById(props.invoiceId)
      // 确保金额字段是数字类型
      Object.assign(formData, {
        ...data,
        totalAmount: typeof data.totalAmount === 'string' ? parseFloat(data.totalAmount) : data.totalAmount,
        taxAmount: typeof data.taxAmount === 'string' ? parseFloat(data.taxAmount) : data.taxAmount,
        totalTaxAmount: typeof data.totalTaxAmount === 'string' ? parseFloat(data.totalTaxAmount) : data.totalTaxAmount
      })
    } catch (error: any) {
      ElMessage.error('获取发票详情失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
})
</script>

<style scoped>
.invoice-edit-container {
  padding: 20px;
}

.edit-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}
</style>